package com.timk.goserver.client.board;

import java.util.ArrayList;
import java.util.Iterator;

import com.timk.goserver.client.compatibility.Point;
import com.timk.goserver.client.sgf.SGFUtils;

/**
 * ResultCommand is used to generate the last SGF node with territory
 * markings and the game result.
 * @author TKington
 *
 */
public class ResultCommand extends AbstractCommand {
	private final String result;
	private final double komi;
	
	/**
	 * Creates a ResultCommand
	 * @param controller the BoardController
	 * @param board the Board
	 * @param prevMove the previous move
	 * @param result the game result
	 * @param komi the game komi
	 */
	public ResultCommand(BoardController controller, Board board, 
			PassCommand prevMove, String result, double komi) {
		super(controller, board, 0, prevMove, null);
		
		this.result = result;
		this.komi = komi;
	}

	public Point getKoPoint() {
		return null;
	}

	public Point getLocation() {
		return null;
	}

	public void localDoIt() { /* do nothing */ }

	public void localUndoIt() { /* do nothing */ }

	public void toSgf(StringBuffer buf) {
		ArrayList blackTerr = new ArrayList();
		ArrayList whiteTerr = new ArrayList();

		int size = board.getSize();
		for(int i = 0; i < size; i++) {
			for(int j = 0; j < size; j++) {
				int mark = board.getMarkAt(i, j);
				if(mark == Board.MARK_TERRBLACK) {
					blackTerr.add(new Point(i, j));
				} else if(mark == Board.MARK_TERRWHITE) {
					whiteTerr.add(new Point(i, j));
				}
			}
		}
		
		buf.append(";N[RESULT]TB");
		for (Iterator iter = blackTerr.iterator(); iter.hasNext();) {
			Point p = (Point) iter.next();
			buf.append('[');
			SGFUtils.pointToString(p, buf);
			buf.append(']');
		}
		
		buf.append("TW");
		for (Iterator iter = whiteTerr.iterator(); iter.hasNext();) {
			Point p = (Point) iter.next();
			buf.append('[');
			SGFUtils.pointToString(p, buf);
			buf.append(']');
		}
		
		buf.append("C[Black: ").append(controller.getBlackScore());
		buf.append("\nWhite: ").append(controller.getWhiteScore());
		buf.append(" + ").append(komi).append(" komi = ");
		buf.append((controller.getWhiteScore() + komi));
		buf.append("\nResult: ").append(result).append(']');
	}
}
